const app = getApp();
var util = require('../../utils/util')
var base = new util.Base64()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    host: wx.$.host,
    navH: app.data.navHeight,
    userInfo: "",
    Cardtotal: 0,
    cycleArr: [],
    recommend: [],
    /* 弹框 */
    isShowCertificate: true,  // 弹窗蒙层
    memberSignin: '',    // 状态码
    cardsdata: [],      // 卡列表数据
    selectCardId: '',   // 选中的card id
    cardsdataindex: '',
    sharefriend: false,
    /* 弹框 --end */
    isTipSignModalShow: true,  // 确认签到弹窗显示隐藏
    isMap: true,
    iSsignin: 0,
    timer: '',//定时器名字
    countDownNum: '5'//倒计时初始值
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.data.jsonPage) {
      var nvabarData = {
        title: app.data.jsonPage.mine.title,
        bgclase: "url(https://vstartup-1253985024.cos.ap-beijing.myqcloud.com/zxs_20200119105015.png);background-size:cover;background-repeat: no-repeat;",
        showCapsule: true,
        height: 88
      };
      this.setData({
        pageToconfigure: app.data.jsonPage.mine,
        nvabarData: nvabarData,
      });
    } else {
      var left = this;
      app.getjsonPage = res => {
        var nvabarData = {
          title: res.mine.title,
          bgclase: "rgba(52, 52, 52, 0)",
          showCapsule: false
        };
        left.setData({
          pageToconfigure: res.mine,
          nvabarData: nvabarData,
        });
      };
    }
    // this.getObtainCard();
    // this.getcycleList()
    // this.getList()
    this.mymember()
  },
  showMap() {
    let that = this
    if (this.data.isMap) {
      that.setData({
        isMap: false,
      })
      setTimeout(() => {
        that.setData({
          isMap: true,
        })
      }, 1000)
    }
  },
  // 阻止弹窗下页面滚动
  myCatchTouch() {
    return
  },
  onPageScroll: function (e) {
    this.showMap()
  },
  freeTell: function () {
    wx.makePhoneCall({
      phoneNumber: '13146903883',
    })
  },
  bindselectFunc(e) {
    let getIndex = e.detail; // 获取组件传来的下标
    wx.makePhoneCall({
      phoneNumber: ['13146903883', '18511582917'][getIndex],
    })
    this.setData({
      menuFlag: false,
      Channel: getIndex,
      'cusInfoObj.channel1': getIndex + 1
    })

  },
  showMenuFunc() {
    this.setData({
      contentArr: ['13146903883', '18511582917'],
      menuFlag: true,
      isChannel: '2'
    })
  },
  /* 分享去购买 */
  mymember() {
    wx.$.fetch('api/member/my', {
      hideLoading: false,
      method: 'get',
    }).then(res => {
      if (res.data.code == 200) {
        this.setData({
          integral: res.data.data.integral,
          DaysNum: res.data.data.signin_days,
        })
      }
    })
  },
  getclock() {
    wx.navigateTo({
      url: "/pages/home/home"
    });
  },
  /* 扫描二维码 */
  Sweepcodejudge() {
    app.btnLandingJudgment('', false, true)
    app.AcceptData = res => {
      this.Sweepcode()
    }
  },
  // 确认签到弹窗显示
  showTipModal() {
    this.setData({
      isTipSignModalShow: true,
      isShowCertificate: false
    })
  },
  // 确认签到
  confirmSign() {
    wx.$.recommend_id = 0;
    this.data.cardsdataindex = '';
    this.setData({
      memberSignin: '',
      sharefriend: false,
      isShowCertificate: true,
      isTipSignModalShow: false
    })
    this.Sweepcode()
  },
  Sweepcode() {
    let left = this
    left.getMemberSignin()
    // wx.scanCode({
    //   success(res) {
    //     let path = res.path
    //       ? res.path
    //       : decodeURIComponent(base.decode(res.rawData));
    //     let data = util.getQueryObject(path);
    //     if (data.Signintype) {
    //       left.getMemberSignin()
    //     } else {
    //       wx.showToast({
    //         title: '请扫签到二维码',
    //         icon: 'none',
    //         mask: true,
    //         duration: 5000,
    //       })
    //     }
    //   },
    //   fail(res) {
    //     wx.showToast({
    //       title: '扫码失败请重新扫码',
    //       icon: 'none',
    //       mask: true,
    //       duration: 4000,
    //     })
    //   },
    // })
  },
  // 选择未激活的卡片
  selectCurCard(selectItem) {
    this.setData({
      selectCardId: selectItem.currentTarget.dataset.id
    })
  },
  countDown: function () {
    let that = this;
    let countDownNum = that.data.countDownNum;//获取倒计时初始值
    //如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
    that.setData({
      timer: setInterval(function () {//这里把setInterval赋值给变量名为timer的变量
        //每隔一秒countDownNum就减一，实现同步
        countDownNum--;
        //然后把countDownNum存进data，好让用户知道时间在倒计着
        that.setData({
          countDownNum: countDownNum
        })
        //在倒计时还未到0时，这中间可以做其他的事情，按项目需求来
        if (countDownNum == 0) {
          //这里特别要注意，计时器是始终一直在走的，如果你的时间为0，那么就要关掉定时器！不然相当耗性能
          //因为timer是存在data里面的，所以在关掉时，也要在data里取出后再关闭
          clearInterval(that.data.timer); 
          //关闭定时器之后，可作其他处理codes go here
          that.showCertificatec()
        }
      }, 1000)
    })
  },
  /* 签到 */
  getMemberSignin() {
    let left = this;
    const member_card_id = this.data.selectCardId ? this.data.selectCardId : '';
    wx.$.fetch(`api/member/signin`, {
      method: 'POST',
      data: {
        type: 1,
        member_card_id: member_card_id
      },
    }).then(res => {
      if (res.data.code == 200) {
        left.setData({
          isShowCertificate: false,
          memberSignin: res.data.code
        })
        left.data.selectCardId = '';
        this.countDown();
      } else if (res.data.code == 30007) {
        left.setData({
          isShowCertificate: false,
          memberSignin: res.data.code
        })
      } else if (res.data.code == 30006) {
        left.setData({
          isShowCertificate: false,
          memberSignin: res.data.code,
          cardsdata: res.data.data.cards,
          selectCardId: res.data.data.cards[0].id
        })
      } else {
        wx.showToast({
          title: res.data.data.message,
          icon: 'none',
          mask: true,
          duration: 4000,
        })
      }
    })
  },
  /* 跳转手机号授权页面 */
  getbindTel() {
    wx.navigateTo({
      url: '/pages/bindTel/bindTel',
      success: function (res) {
        res.eventChannel.emit('TransferOfData2', {
          url: '',
          typeurl: false,
          executeType: false,
        })
      },
    })
  },
  /* 开启自习室或购买卡 */
  btnUse() {
    wx.$.fetch('api/member/has-available-card', {
      hideLoading: false,
      method: 'get',
    }).then(res => {
      if (res.data.code == 200) {
        if (res.data.data == 1) {
          this.Sweepcode()
        } else {
          this.purchaseVip();
        }
      } else {
        wx.showModal({
          title: "提示",
          content: res.data.msg,
          confirmColor: "#50B23F",
          showCancel: false
        });
      }
    })
  },
  Jumpcards() {
    wx.navigateTo({
      url: "/pages/openingVip/openingVip"
    });
  },
  /* 选中得卡 */
  getSwiperitem(current) {
    let index = current.detail.current;
    this.data.cardsdataindex = this.data.cardsdata[index].id;
  },
  /* 购买vip */
  purchaseVip() {
    this.showCertificatec()
    wx.navigateTo({
      url: "/pages/openingVip/openingVip"
    });
  },
  /* 分享去购买 */
  sharePurchaseVip() {
    wx.navigateTo({
      url: "/pages/openingVip/openingVip"
    });
    this.data.cardsdataindex = '';
    this.setData({
      memberSignin: '',
      sharefriend: false,
      isShowCertificate: true,
    })
  },
  getObtainCard() {
    wx.$.fetch('api/member/card/my', {
      method: 'get'
    }).then(res => {
      let data = res.data.data.data;
      this.setData({
        cardsList: data
      })
    })
  },
  /* 关闭弹框 */
  showCertificatec() {
    wx.$.recommend_id = 0;
    this.data.cardsdataindex = '';
    this.setData({
      memberSignin: '',
      sharefriend: false,
      isShowCertificate: true,
      countDownNum: '5'
    })
    this.getcycleList()
    this.getObtainCard()
    this.mymember()
    var myDate = new Date();
    var tYear = myDate.getFullYear();
    var tMonth = myDate.getMonth() + 1;
    let calendar = this.selectComponent('#calendar')
    calendar.createDays(tYear, tMonth)
  },
  MonthDays(e) {
    var myDate = new Date();
    var tYear = myDate.getFullYear();
    var tMonth = myDate.getMonth() + 1;
    var tDay = myDate.getDate()
    var iSsignin = ''
    var time = `${tYear}-${this.zero(tMonth)}-${this.zero(tDay)}`
    if (e.detail.length > 0) {
      for (let j = 0; j < e.detail.length; j++) {
        if (e.detail[j].date_at === time) {
          iSsignin = 1
        } else {
          iSsignin = 0
        }
      }
      this.setData({
        iSsignin: iSsignin
      })
    }
  },
  zero: function (i) {
    return i >= 10 ? i : '0' + i;
  },
  // 会员卡列表
  getList() {
    wx.$.fetch('api/cards', {
      hideLoading: false,
      method: 'GET',
      data: {
        is_recommend: 1
      }
    }).then(res => {
      this.setData({
        // content_html: res.data.data[0].desc,
        recommend: res.data.data
      })
    })
  },
  getcycleList() {
    wx.$.fetch('/api/member/signin/cycle', {
      hideLoading: false,
      method: 'GET'
    }).then(res => {
      this.setData({
        cycleArr: res.data.data
      })
    })
  },
  /* 绑定手机号 */
  getBindTel() {
    wx.navigateTo({
      url: "/pages/bindTel/bindTel"
    });
  },
  /* 使用记录 */
  Myrecord() {
    wx.navigateTo({
      url: "/pages/record/record"
    });
  },
  /* 跳转我的vip */
  getmyVip() {
    wx.navigateTo({
      url: "/pages/myVip/myVip"
    });
  },
  /* 购买vip */
  purchaseVip() {
    wx.navigateTo({
      url: "/pages/openingVip/openingVip"
    });
  },
  settings() {
    wx.$.fetch('/api/settings', {
      method: 'get',
      data: {
        type: 'mini_template'
    }
    }).then(res => {
      // console.log(res)
    })
  },
  /* 跳转分享好友 */
  getshare() {
    let that = this;
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        console.log(res)
        
      }
    })
    wx.requestSubscribeMessage({
      tmplIds: ['TEtCC1267hiVi0rkpi4tDEh3yEshyVKFDuPL9UwKunA'],
      success(res) {
        // that.setData({
        //   textcontent: '提示：授权成功'
        // })
        wx.navigateTo({
          url: "/pages/sharePoster/sharePoster"
        });
      },
      fail(res) {
        // that.setData({
        //   textcontent: '提示：授权失败'
        // })
        wx.navigateTo({
          url: "/pages/sharePoster/sharePoster"
        });
      }
    })
    // wx.navigateTo({
    //   url: "/pages/sharePoster/sharePoster"
    // });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      countDownNum: '5'
    })
    this.getcycleList()
    this.getObtainCard()
    this.getcycleList()
    this.mymember()
    var myDate = new Date();
    var tYear = myDate.getFullYear();
    var tMonth = myDate.getMonth() + 1;
    let calendar = this.selectComponent('#calendar')
    calendar.createDays(tYear, tMonth)
    if (wx.getStorageSync("vs-info")) {
      this.setData({
        userInfo: wx.getStorageSync("vs-info")
      });
    } else {
      app.btnLandingJudgment('', false, false);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { }
});
